<?php

namespace App\Http\Validate\OpenShop\ShopEngineeringConstruction;

use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\UploadFileResourceEnum;
use App\Http\Validate\AbstractBaseValidate;
use App\Models\OpenShop\ShopEngineeringConstruction\OpenShopEngineeringConstructionModel;
use App\Service\OpenShop\Merchant\OrderProgressService;
use Illuminate\Support\MessageBag;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Kuafu\File\FileUtil;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

/**
 * [ 订单业务验证 ] - 校验规则
 *
 * @OpenShopUserContractValidate
 * @package App\Http\Controllers
 * @date 2022/03/01 02:35:56
 * @author GreenLeaf <786407418@qq.com>
 */
class ShopEngineeringConstructionValidate extends AbstractBaseValidate
{
    public function registerValidateRules(): void
    {
        // TODO: Implement registerValidateRules() method.
    }

    public function getAttributes(): array
    {
        // TODO: Implement getAttributes() method.
        return [
            "id"                                => "",
            "mainProcessId"                     => "开店主流程id",
            "orderNo"                           => "开店订单号",
            "step"                              => "营建步骤 [ 0:筹备部等待施工进场 1:筹备部确认施工进场 2:筹备部确认施工完成 ]",
            "engineeringConstructionStartTime"  => "施工进场时间",
            "shopImages"                        => "门店图片",
            "engineeringConstructionFinishTime" => "施工完成时间",
            "createdAt"                         => "创建时间",
            "createdByUid"                      => "创建人",
            "updatedAt"                         => "修改时间",
            "updatedByUid"                      => "修改人",
        ];
    }

    public function getMessages(): array
    {
        // TODO: Implement getMessages() method.
        return [
            "orderNo.exists" => "当前订单号暂不支持此操作"
        ];
    }

    public function getRules(): array
    {
        // TODO: Implement getRules() method.
        return [
            "id"                                => "bail|required|int",
            "mainProcessId"                     => "bail|required|int",
            "orderNo"                           => "bail|required|string",
            "step"                              => "bail|required",
            "engineeringConstructionStartTime"  => "bail|required|string|date_format:Y-m-d",
            "engineeringConstructionFinishTime" => "bail|required|string|date_format:Y-m-d",
            "createdAt"                         => "bail|required|int",
            "createdByUid"                      => "bail|required|int",
            "updatedAt"                         => "bail|required|int",
            "updatedByUid"                      => "bail|required|int",
            "finishStatus"                      => "bail|required|int|in:" . enumTransToRules(OpenShopEngineeringConstructionModel::FINISH_STATUS_MAP),
            "shopHeaderImages"                  => "bail|sometimes|array",
            "shopInnerImages"                   => "bail|sometimes|array",
            "shopOutNightImages"                => "bail|sometimes|array"
        ];
    }

    /**
     * @param array $params
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function engineeringConstructionStartValidate(array $params)
    {
        return self::getInstance()->validate(
            ["orderNo", "engineeringConstructionStartTime"],
            $params,
            [
                "orderNo" => [
                    "bail",
                    "required",
                    Rule::exists("open_shop_engineering_construction", "orderNo")
                        ->where("step", MainProcessEnum::ENGINEER_CONSTRUCT_STAY)
                ]
            ],
            true,
            function (array $params) {
                $params["engineeringConstructionStartTime"] = strtotime($params["engineeringConstructionStartTime"]);
                return $params;
            }
        );
    }

    /**
     * @param array $params
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function engineeringConstructionFinish(array $params)
    {
        return self::getInstance()->validate(
            [
                "orderNo",
                "engineeringConstructionFinishTime",
                "finishStatus"
            ],
            $params,
            [
                "orderNo" => [
                    "bail",
                    "required",
                    Rule::exists("open_shop_engineering_construction", "orderNo")
                        ->where("step", MainProcessEnum::ENGINEER_CONSTRUCT_START)
                ]
            ],
            true,
            function (array $params) {
                $params["engineeringConstructionFinishTime"] = strtotime($params["engineeringConstructionFinishTime"]);
                return $params;
            }
        );
    }

    /**
     * @param array $params
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function startDetailValidate(array $params)
    {
        return self::getInstance()->validate(
            ["orderNo"],
            $params,
            [
                "orderNo" => Rule::exists("open_shop_engineering_construction", "orderNo")
                                 ->where(function ($query) {
                                     $query->where("step", ">", MainProcessEnum::ENGINEER_CONSTRUCT_STAY);
                                 })
            ]
        );
    }


    /**
     * @param array $params
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function finishDetailValidate(array $params)
    {
        return self::getInstance()->validate(
            ["orderNo"],
            $params,
            [
                "orderNo" => Rule::exists("open_shop_engineering_construction", "orderNo")
                                 ->where(function ($query) {
                                     $query->where("step", ">", MainProcessEnum::ENGINEER_CONSTRUCT_START);
                                 })
            ]
        );
    }

    /**
     * 附件校验
     *
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function attachValidate(array $requestParams, int $origin = 0)
    {
        return self::getInstance()->validate(
            ["shopHeaderImages", "shopInnerImages", "shopOutNightImages"],
            $requestParams,
            null,
            true,
            function (array $params) use ($origin, $requestParams) {
                $insertData = [];
                $uid        = getRmsUserInfoByAuth()->id;
                collect($params)->each(function ($v, $k) use ($origin, &$insertData, $requestParams, $uid) {
                    collect($v)->each(function ($img) use ($origin, &$insertData, $k, $requestParams, $uid) {
                        $position = array_keys(UploadFileResourceEnum::ENGINEERING_CONSTRUCTION_MAP, $k)[0];
                        array_push($insertData, [
                            "orderNo"      => $requestParams["orderNo"],
                            "position"     => $position,
                            "url"          => !$origin ? getPrivateFileKey($img) : str_replace(FileUtil::domain(), '', $img),
                            "isPublic"     => $origin,
                            "createdAt"    => time(),
                            "createdByUid" => $uid
                        ]);
                    });
                });
                return $insertData;
            }
        );
    }

    /**
     * @param array $params
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function engineeringConstructionUpdate(array $params)
    {
        return self::getInstance()->validate(
            [
                "orderNo",
                "engineeringConstructionStartTime",
                "engineeringConstructionFinishTime",
                "finishStatus"
            ],
            $params,
            [
                "orderNo" => [
                    "bail",
                    "required",
                    Rule::exists("open_shop_engineering_construction", "orderNo")
                        ->where(function ($query) {
                            $query->where("step", ">", MainProcessEnum::ENGINEER_CONSTRUCT_START);
                        })
                ]
            ],
            true,
            function (array $params) {
                $params["engineeringConstructionStartTime"]  = strtotime($params["engineeringConstructionStartTime"]);
                $params["engineeringConstructionFinishTime"] = strtotime($params["engineeringConstructionFinishTime"]);
                return $params;
            }
        );
    }

    /**
     * @param array $params
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function engineeringConstructionRealTimeUpdate(array $params)
    {
        return self::getInstance()->validate(
            [
                "orderNo",
            ],
            $params,
            [
                "orderNo" => [
                    "bail",
                    "required",
                    Rule::exists("open_shop_engineering_construction", "orderNo")
                        ->where("step", MainProcessEnum::ENGINEER_CONSTRUCT_START)
                ]
            ],
            true,
            function (array $params) {
                return $params;
            }
        );
    }
}
